package com.imooc.service.impl;

import com.alibaba.fastjson.JSON;
import com.imooc.common.converter.OrderMaser2OrderDTOConverter;
import com.imooc.common.dto.CartDTO;
import com.imooc.common.dto.OrderDTO;
import com.imooc.common.enums.OrderStatusEnum;
import com.imooc.common.enums.PayStatusEnum;
import com.imooc.common.enums.ResultEnum;
import com.imooc.common.exception.SelllException;
import com.imooc.common.utils.KeyUtil;
import com.imooc.dataobject.OrderDetail;
import com.imooc.dataobject.OrderMaster;
import com.imooc.dataobject.ProductInfo;
import com.imooc.repository.OrderDetailRepository;
import com.imooc.repository.OrderMasterRepository;
import com.imooc.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMasterRepository masterRepository;

    @Autowired
    OrderDetailRepository detailRepository;

    @Autowired
    ProductService productService;

    @Autowired
    PayService payService;

    @Autowired
    PushMessage pushMessage;

    @Autowired
    WebSocket webSocket;

    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        String orderId = KeyUtil.genUniqueKey();
        // 1. 查询商品
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productService.findOne(orderDetail.getProductId());
            if (Objects.isNull(productInfo)) {
                throw new SelllException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            // 2. 计算总价
            orderAmount = new BigDecimal(orderDetail.getProductQuantity())
                    .multiply(productInfo.getProductPrice())
                    .add(orderAmount);

            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            detailRepository.save(orderDetail);
        }

        // 3. 写入订单数据库
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        orderDTO.setOrderAmount(orderAmount);
        orderDTO.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderDTO.setPayStatus(PayStatusEnum.WAIT.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        masterRepository.save(orderMaster);

        // 4. 扣库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());

        productService.decreaseStock(cartDTOList);

        // 发送消息
        webSocket.sendMessage("有新的订单");

        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster = masterRepository.findById(orderId).orElse(null);
        log.info("orderMaster返回：{}", JSON.toJSONString(orderMaster));
        if (orderMaster == null) {
            throw new SelllException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = detailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new SelllException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findByBuyerOpenid(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> masterPage = masterRepository.findByBuyerOpenid(buyerOpenid, pageable);
        List<OrderDTO> orderDTOList = OrderMaser2OrderDTOConverter.convertList(masterPage.getContent());
        Page<OrderDTO> orderDTOPage = new PageImpl(orderDTOList, pageable, masterPage.getTotalElements());
        return orderDTOPage;
    }

    @Override
    public Page<OrderDTO> findAll(Pageable pageable) {
        Page<OrderMaster> masterPage = masterRepository.findAll(pageable);
        List<OrderDTO> orderDTOList = OrderMaser2OrderDTOConverter.convertList(masterPage.getContent());
        Page<OrderDTO> orderDTOPage = new PageImpl(orderDTOList, pageable, masterPage.getTotalElements());
        return orderDTOPage;
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        OrderMaster master = new OrderMaster();
        String orderId = orderDTO.getOrderId();
        Integer orderStatus = orderDTO.getOrderStatus();
        // 更新订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderStatus)) {
            log.error("订单状态不正确：{}", orderStatus);
            throw new SelllException(ResultEnum.ORDERD_STATUS_ERROR);
        }
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO, master);
        OrderMaster save = masterRepository.save(master);
        if (save == null) {
            log.error("订单状态更新失败");
            throw new SelllException(ResultEnum.ERROR);
        }

        // 恢复库存
        List<OrderDetail> orderDetailList = detailRepository.findByOrderId(orderId);
        List<CartDTO> cartDTOList = orderDetailList
                .stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());

        productService.increaseStock(cartDTOList);

        // 如果已支付，退款
        if (PayStatusEnum.SUCCESS.getCode().equals(master.getPayStatus())) {
            payService.refund(orderDTO);
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();

        Integer orderStatus = orderDTO.getOrderStatus();
        if (!OrderStatusEnum.NEW.getCode().equals(orderStatus)) {
            log.error("订单状态不正确：{}", orderStatus);
            throw new SelllException(ResultEnum.ORDERD_STATUS_ERROR);
        }

        orderDTO.setOrderStatus(OrderStatusEnum.FINISH.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = masterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("订单状态更新失败");
            throw new SelllException(ResultEnum.ERROR);
        }

        // 推送消息消息
        pushMessage.orderStatus(orderDTO);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();
        Integer orderStatus = orderDTO.getOrderStatus();
        if (!OrderStatusEnum.NEW.getCode().equals(orderStatus)) {
            log.error("订单状态不正确：{}", orderStatus);
            throw new SelllException(ResultEnum.ORDERD_STATUS_ERROR);
        }

        Integer payStatus = orderDTO.getPayStatus();
        if (!PayStatusEnum.WAIT.getCode().equals(payStatus)) {
            log.error("支付状态不正确：{}", payStatus);
            throw new SelllException(ResultEnum.PAY_STATUS_ERROR);
        }

        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = masterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("支付状态更新失败");
            throw new SelllException(ResultEnum.ERROR);
        }
        return orderDTO;
    }
}
